import requests
import json

# 你的飞书应用的APP_ID
app_id = "cli_a7bc1b23853b9013"
# 你的飞书应用的APP_SECRET
app_secret = "ChsiFTzVeNJQVgOXkKdwrcNoIFw3BKYT"
# 飞书表格应用的app_token
app_token = "AGULbGJdIaCWyUsC1PKcYLnsn8b"
# 飞书表格的table_id
table_id = "tblRYj7NzwxwwyfJ"

# 获取今天的日期，年月日
import datetime
today = datetime.datetime.now()
year = today.year
month = today.month
day = today.day
print(f"今天是{year}年{month}月{day}日")

# 新增一条数据到飞书表格-热量摄入
def insert_data_to_intake_table(kcal, fat_gram, protein_gram, carbohydrate_gram, food_name, total_weight):

    # 获取访问令牌（access token）
    token_url = f"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    token_payload = {
        "app_id": app_id,
        "app_secret": app_secret
    }
    token_response = requests.post(token_url, json=token_payload)
    access_token = json.loads(token_response.text)["tenant_access_token"]
    print(f"访问令牌: {access_token}")

    # 构造要创建记录的请求体数据
    record_data = {
        "fields": {
            "人员": "张同学",
            "热量(kcal)": kcal,
            "脂肪(g)": fat_gram,
            "蛋白质（g）": protein_gram,
            "碳水化合物（g）": carbohydrate_gram,
            "食物名称": food_name,
            "重量g": total_weight
        }
    }

    # 构造创建记录的请求URL
    create_record_url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records"

    # 设置请求头，包含访问令牌等必要信息
    headers = {
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Bearer {access_token}"
    }

    # 将记录数据转换为JSON格式字符串
    json_data = json.dumps(record_data)

    # 发起创建记录的请求
    create_response = requests.post(create_record_url, headers=headers, data=json_data)

    # 处理请求失败的情况
    if create_response.status_code != 200:
        print(f"创建记录失败，状态码: {create_response.status_code}，错误信息: {create_response.text}")
        return

    # 处理请求成功的情况，输出创建成功的记录信息
    created_record = json.loads(create_response.text)
    print(json.dumps(created_record, indent=4))

def query_bitable_records_with_requests():
    """
    使用requests库查询飞书多维表格记录的函数
    """
    # 以下假设这些是从飞书开发者后台获取到的相关认证信息等，实际使用中需替换为真实有效的值
    APP_ID = "cli_a7bc1b23853b9013"
    APP_SECRET = "ChsiFTzVeNJQVgOXkKdwrcNoIFw3BKYT"
    APP_TOKEN = "AGULbGJdIaCWyUsC1PKcYLnsn8b"
    TABLE_ID = "tblRYj7NzwxwwyfJ"
    VIEW_ID = "vewqxKxWDu"

    # 获取访问令牌
    access_token_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    access_token_headers = {
        "Content-Type": "application/json"
    }
    access_token_data = {
        "app_id": APP_ID,
        "app_secret": APP_SECRET
    }
    access_token_response = requests.post(access_token_url, headers=access_token_headers, data=json.dumps(access_token_data))
    if access_token_response.status_code!= 200:
        print(f"获取访问令牌失败，状态码: {access_token_response.status_code}，错误信息: {access_token_response.text}")
        return None
    access_token = json.loads(access_token_response.text)["tenant_access_token"]

    # 构造请求数据
    request_data = {
        "view_id": VIEW_ID,
        "field_names": ["热量(kcal)", "脂肪(g)", "蛋白质（g）", "碳水化合物（g）"],
        "filter": {
            "conjunction": "and",
            "conditions": [
                {
                    "field_name": "年",
                    "operator": "is",
                    "value": [f"{year}"]
                },
                {
                    "field_name": "月",
                    "operator": "is",
                    "value": [f"{month}月"]
                },
                {
                    "field_name": "日",
                    "operator": "is",
                    "value": [f"{day}"]
                }
            ]
        },
        "automatic_fields": False
    }

    # 构造请求URL和请求头
    request_url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/search"
    request_headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }

    # 发起请求
    response = requests.post(request_url, headers=request_headers, data=json.dumps(request_data))

    # 处理失败返回
    if response.status_code!= 200:
        print(f"查询飞书多维表格记录失败，状态码: {response.status_code}，错误信息: {response.text}")
        return None

    # 处理业务结果
    response_data = json.loads(response.text)
    records = (response_data['data']['items'])

    return records


